<?php
namespace app\teacher\controller;

use app\home\model\Teacher;
use Think\Db;
use think\Request;
use app\teacher\model\Apply;
use app\teacher\model\Attendance;
use app\teacher\model\User;
use think\Session;

class  Attendancess extends Base
{
   //签到列表
   public function index(){
     $teacher = $this->user_info();

     //查询今年所有的录取学生
     $apply = collection(Apply::where(["status"=>"2","grade"=>date("Y",time())])->order("teacher_id","asc")->select())->toArray();
     foreach($apply as $key=>$val){
       $student = User::where(["id"=>$val['userid']])->find()->toArray();
       $teacher = Teacher::get($val['teacher_id']);
       $apply[$key]['user']=$student;
       $apply[$key]['teacher']=$teacher;
     }
     $arr = [
       "setting"=>$this->getAllSetting(),
       "apply"=>$apply
     ];
     return view("index",$arr);
   }

   //今日已经签到
   public function  today_atten(){
     $atten =  collection(Attendance::where(["startDate"=>date("Y-n-j")])->select())->toArray();
     return json($atten);
   }

   //查看该老师是否可以点名
    public function is_atten(){
     if(Session::has("teacher_infos")){
       $user = $this->user_info();
        return json(["c" => $user['is_attendances']]);
      }else{
        return json(["c" => "login" ]);
      }
    }

   //签到
   public function set_atten(Request $request){
     $data = $request->post();
     $atten = Attendance::where(["startDate" => date("Y-n-j"), "userid" => $data['userid']])->find();
     if($data['name'] == "撤销") {
       if($atten){
          Attendance::destroy($atten["id"]);
          Db::query("alter table attendance  auto_increment = 0");
       }
       $this->success("撤销成功");
     }else{
       if ($atten) {
         $res = Attendance::update(["userid" => $data["userid"], "name" => $data['name'], "id" => $atten["id"]]);
       } else {
         $data['startDate'] = date("Y-n-j");
         $res = Attendance::create($data);
       }
     }
     //返回结果
     if ($res) {
       $this->success("修改成功");
     } else {
       $this->error("修改失败");
     }

   }
}